package com.xiaoyu.lanling.feature.invite

import `in`.srain.cube.util.UTUtil
import android.os.Bundle
import android.view.LayoutInflater
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.Animation
import android.view.animation.ScaleAnimation
import com.xiaoyu.base.app.AppContext
import com.xiaoyu.base.app.GlobalUI
import com.xiaoyu.base.data.UserData
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.base.utils.RxUtils
import com.xiaoyu.base.utils.extensions.copy
import com.xiaoyu.base.utils.extensions.getViewTag
import com.xiaoyu.base.utils.extensions.setViewTag
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.AppCompatToolbarActivity
import com.xiaoyu.lanling.event.invite.InvitationWithDrawListEvent
import com.xiaoyu.lanling.event.invite.InviteTipEvent
import com.xiaoyu.lanling.feature.invite.data.InviteData
import com.xiaoyu.lanling.feature.invite.dialog.InviteShareDialog
import com.xiaoyu.lanling.feature.invite.dialog.InviteTipDialog
import com.xiaoyu.lanling.feature.invite.fragment.InviteBoardFragment
import com.xiaoyu.lanling.feature.invite.fragment.InviteEarningDetailFragment
import com.xiaoyu.lanling.feature.invite.fragment.InviteListFragment
import com.xiaoyu.lanling.lifecycle.disposeOn
import com.xiaoyu.lanling.util.TextViewUtil
import com.xiaoyu.lanling.view.FragmentAdapter
import com.xiaoyu.lanling.view.OnShowFragment
import io.reactivex.Flowable
import kotlinx.android.synthetic.main.activity_invite.*
import kotlinx.android.synthetic.main.invite_ontv_item.view.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class InviteActivity : AppCompatToolbarActivity() {
    private val requestTag = Any()
    val PAGE_EARN = 1
    val PAGE_INVITE = 2
    val PAGE_BOARD = 0
    override fun onCreateSafelyAfterAppFinishInit(savedInstanceState: Bundle?) {
        setLightStatusBar()
        setContentView(R.layout.activity_invite)
        initView()
        initBind()
        initEvent()
        initData()
    }

    override fun onResumeSafelyAfterAppFinishInit(isFirstTimeResume: Boolean) {
        super.onResumeSafelyAfterAppFinishInit(isFirstTimeResume)
        logEventForEnter()
    }

    private fun logEventForEnter() {
        UTUtil.getInstance().logEvent("enter_invitation_page")
        UTUtil.getInstance().flushLogEvent()
    }

    private fun initData() {
        InviteData.getInviteTip(requestTag)
        InviteData.getInvitationBannerWithDrawList(requestTag)
        InviteData.getOtherWithDrawMessage(requestTag)
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(this, object : SimpleEventHandler() {
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: InviteTipEvent) {
                tip.setViewTag(event.tips)
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: InvitationWithDrawListEvent) {
                showViewFlipData(event)
            }
        })
    }

    private fun showViewFlipData(event: InvitationWithDrawListEvent) {
        val list = event.list
        Flowable.fromIterable(list)
                .map {
                    val rootView = LayoutInflater.from(AppContext.getContext()).inflate(R.layout.invite_ontv_item, null, false)
                    TextViewUtil.stripUnderlinesAndClickable(rootView.invite_flip_text, it)
                    rootView
                }
                .compose(RxUtils.ioToMainFlowableScheduler())
                .subscribe({
                    viewFlipper.addView(it)
                }, {

                }, {
                    viewFlipper.startFlipping()
                })
                .disposeOn(this)
    }

    private fun initView() {
        initToolbar()
        title = AppContext.getString(R.string.invite_invite_friend)
        view_pager.setSmoothScroll(false)
        val fragmentList = mutableListOf<OnShowFragment>()
        fragmentList.add(InviteBoardFragment())
        fragmentList.add(InviteEarningDetailFragment())
        fragmentList.add(InviteListFragment())
        val fragmentAdapter = FragmentAdapter(supportFragmentManager, fragmentList, listOf("", "", ""))
        view_pager.adapter = fragmentAdapter
        view_pager.currentItem = PAGE_BOARD
        view_pager.offscreenPageLimit = fragmentList.size
        invite_code.text = UserData.getInstance().uid
        val scaleAnimation = ScaleAnimation(0.85f, 1f, 0.85f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
        scaleAnimation.repeatMode = Animation.REVERSE
        scaleAnimation.repeatCount = Animation.INFINITE
        scaleAnimation.duration = 500
        scaleAnimation.interpolator = AccelerateDecelerateInterpolator()
        invite_immediately.startAnimation(scaleAnimation)
    }

    private fun initBind() {
        invite_tab_layout.setOnCheckedChangeListener { radioGroup, checkedId ->
            when (checkedId) {
                R.id.invite_earning_detail_tab -> {
                    invite_tab_indicator.setImageResource(R.drawable.invite_earnings_detail_icon)
                    view_pager.currentItem = PAGE_EARN
                }
                R.id.invite_list_tab -> {
                    invite_tab_indicator.setImageResource(R.drawable.invite_invite_list_icon)
                    view_pager.currentItem = PAGE_INVITE
                }
                R.id.invite_board_tab -> {
                    invite_tab_indicator.setImageResource(R.drawable.invite_inviting_board_icon)
                    view_pager.currentItem = PAGE_BOARD
                }
                else -> {
                    invite_tab_indicator.setImageResource(R.drawable.invite_earnings_detail_icon)
                    view_pager.currentItem = PAGE_BOARD
                }
            }
        }
        invite_immediately.setOnClickListener {
            InviteShareDialog.show(supportFragmentManager)
        }
        tip.setOnClickListener {
            val tip = it.getViewTag<String>() ?: return@setOnClickListener
            InviteTipDialog.create(tip).show(supportFragmentManager, InviteTipDialog.TAG)
        }
        invite_code_layout.setOnClickListener {
            copy(UserData.getInstance().uid)
            GlobalUI.getInstance().showToast(R.string.invite_copy_success_toast)
        }
    }
}